package com.tian.controller.system;

import com.tian.annotation.ArgsLogAnnotation;
import com.tian.entity.ActiverUser;
import com.tian.util.ImageVerificationCode;
import com.tian.util.ResultObj;
import com.tian.util.WebUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import com.tian.config.RedisConfig;

/**
 * @author tianwc  公众号：java后端技术全栈、面试专栏
 * @version 1.0.0
 * @date 2023年04月25日 20:34
 * 博客地址：<a href="http://woaijava.cc/">博客地址</a>
 * <p>
 * 用户登录管理
 */
@RestController
@RequestMapping("/login")
public class LoginController {

 /*   @Resource
    private LoginfoService loginfoService;*/

    @Resource
    private RedisConfig redisConfig;

    @Resource
    private RedissonClient redissonClient;

    @ArgsLogAnnotation
    @RequestMapping("/getVerifiCode")
    @SuppressWarnings("rawtypes")
    public void getVerifiCode(HttpServletResponse response, HttpSession session) throws IOException {
        Map map = ImageVerificationCode.generateCodeAndPic();
        ServletOutputStream out = response.getOutputStream();
        BufferedImage img = (BufferedImage) map.get("codePic");
        String securityCode = (String) map.get("code");
        session.setAttribute("securityCode", securityCode);
        ImageIO.write(img, "jpg", response.getOutputStream());

    }

    @ArgsLogAnnotation
    @RequestMapping("/login")
    public ResultObj login(String loginname, String pwd, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(loginname, pwd);
        request.setCharacterEncoding("utf-8");
        String sessionCode = (String) request.getSession().getAttribute("securityCode");
        String code = request.getParameter("code");
        /*if (!code.equals(sessionCode)) {
            return ResultObj.LOGIN_ERROR_CODE;
        }*/
        try {

            RLock lock = redissonClient.getLock("myLock");
            boolean res = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if (res) {
                System.out.println("获取分布式锁");
            }

            subject.login(token);
            ActiverUser activerUser = (ActiverUser) subject.getPrincipal();
            WebUtils.getSession().setAttribute("user", activerUser.getUserAdmin());
            //记录登陆日志
          /*  Loginfo entity = new Loginfo();
            entity.setLoginname(activerUser.getUserAdmin().getName() + "-" + activerUser.getUserAdmin().getLoginname());
            entity.setLoginip(WebUtils.getRequest().getRemoteAddr());
            entity.setLogintime(new Date());
            loginfoService.save(entity);*/
            //redis集成测试
            redisConfig.set("warehouse.test.key", "sessionVcode", 20000L);
            System.out.println("缓存：" + redisConfig.get("warehouse.test.key"));
            return ResultObj.LOGIN_SUCCESS;
        } catch (AuthenticationException | InterruptedException e) {
            e.printStackTrace();
            return ResultObj.LOGIN_ERROR_PASS;
        }
    }
}

